package com.controller.sys.user;

import com.common.ErrorCodeEnum;
import com.model.base.Result;
import com.common.anntation.Log;
import com.common.config.Config;
import com.common.emums.BusinessType;

import com.common.exception.BusinessException;
import com.common.utils.file.FileUploadUtils;
import com.common.utils.Md5Utils;
import com.common.utils.ServletUtils;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.core.springSecurity.service.TokenService;
import com.model.dto.sys.userController.UpdatePasswordDTO;
import com.model.dto.sys.userController.UpdateUserInfoDTO;
import com.model.pojo.sys.SysUser;
import com.service.sys.SysUserService;
import com.model.vo.sys.login.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: zql
 * @Description: 用户个人接口列表
 * @Data: 14:03 2021/7/21
 */
@Api(tags = {"个人中心"})
@Slf4j
@RestController
@RequestMapping("/v1")
public class PersonalController {

    @Resource
    SysUserService sysUserService;

    @Resource
    TokenService tokenService;


    /**
     * @Author: zql
     * @Description: 查看当前登录用户信息
     * @Data: 10:41 2021/5/12
     */
    @ApiOperation(value = "查看当前登录用户信息")
    @PostMapping("/getCurrentUser")
    public Result<LoginVO> getUserInfo() {
        return Result.suc(LoginVO.builder().loginUserDetails(SecurityUtils.getLoginUser()).build());
    }

    /**
     * @param file 头像文件
     * @Author: zql
     * @Description: 更新头像
     * @Data: 15:16 2021/5/10
     */
    @ApiOperation(value = "更新个人头像")
    @Log(title = "更新个人头像", businessType = BusinessType.UPDATE,  isSaveResponseData = true)
    @PostMapping("/avatar")
    public Result<Objects> avatar(
            @ApiParam(name = "avatarfile", value = "头像图片", required = true)
            @RequestParam("avatarfile") MultipartFile file) {
        if (!file.isEmpty()) {
            LoginUserDetails loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar;
            try {
                avatar = FileUploadUtils.upload(Config.getAvatarPath(), file);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.fail(ErrorCodeEnum.UPLOAD_FILE);
            }
            //更新数据库用户头像
            SysUser sysUser = new SysUser();
            sysUser.setSysUserId(loginUser.getUser().getSysUserId());
            sysUser.setImagePath(avatar);
            sysUserService.update(sysUser);
            // 更新缓存用户头像
            loginUser.getUser().setImagePath(avatar);
            tokenService.setLoginUser(loginUser);
            return Result.suc();
        }
        return Result.fail(ErrorCodeEnum.UPDATE_USER_IMAGE_FAILED);
    }

    /**
     * @param updatePasswordDTO 更新密码参数
     * @Author: zql
     * @Description: 更新密码
     * @Data: 15:16 2021/5/10
     */
    @ApiOperation(value = "更新个人密码")
    @Log(title = "更新个人密码", businessType = BusinessType.UPDATE,  isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping("/updatePassword")
    public Result<Objects> updatePassword(@RequestBody @Valid UpdatePasswordDTO updatePasswordDTO) {
        SysUser sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        /*原密码必须正确*/
        if (!sysUserService.matches(updatePasswordDTO.getOldPassword(), sysUser.getPassword())) {
            throw new BusinessException(ErrorCodeEnum.USER_OLD_PASSWORD_FAILED);
        }

        sysUser.setPassword(sysUserService.encode(Md5Utils.toUpperCase32(updatePasswordDTO.getNewPassword())));

        sysUserService.update(sysUser);
        return Result.suc();
    }

    /**
     * @param updateUserInfoDTO 修改的用户信息
     * @Author: zql
     * @Description: 更新个人用户信息
     * @Data: 15:19 2021/5/10
     */
    @ApiOperation(value = "更新个人信息")
    @Log(title = "更新个人信息", businessType = BusinessType.UPDATE,  isSaveRequestData = true)
    @PostMapping("/updateUserInfo")
    public Result<Objects> updateUserInfo(@RequestBody @Valid UpdateUserInfoDTO updateUserInfoDTO) {
        LoginUserDetails loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        BeanUtils.copyProperties(updateUserInfoDTO, sysUser);
        sysUserService.update(sysUser);
        //刷新用户缓存
        tokenService.setLoginUser(loginUser);
        return Result.suc();
    }
}
